<template>
  <div :class="{ hasTagsView: needTagsView }" class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <a-card hoverable>
          <a-flex gap="small" wrap="wrap" justify="space-between">
            <a-form ref="queryFormRef" :model="queryParams" layout="inline">
              <a-form-item label="参数名称" prop="configName">
                <a-input v-model:value="queryParams.configName" allow-clear placeholder="请输入参数名称"
                         @change="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
              <a-form-item label="参数键名" prop="configKey">
                <a-input v-model:value="queryParams.configKey" allow-clear placeholder="请输入参数键名"
                         @change="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
              <a-form-item label="系统内置" prop="configType">
                <a-select v-model:vlaue="queryParams.configType" allow-clear placeholder="系统内置"
                          @change="handleQuery" :options="sys_yes_no" :field-names="{label: 'label', value: 'value'}">
                  <template #option="{ label, value }">
                    <a-flex justify="space-between">
                      <span>{{ label }}</span>
                      <span style="color: #999">{{ value }}</span>
                    </a-flex>
                  </template>
                </a-select>
              </a-form-item>
              <a-form-item label="创建时间">
                <a-range-picker
                  v-model:value="dateRange"
                  :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                  :placeholder="['开始日期', '结束日期']" allow-clear format="YYYY-MM-DD HH:mm:ss" range-separator="-"
                  show-time value-format="YYYY-MM-DD HH:mm:ss" @change="handleQuery" />
              </a-form-item>
            </a-form>
            <a-flex justify="end">
              <el-button icon="Search" :loading="loading" round plain type="primary"
                         @click="handleQuery">搜索
              </el-button>
              <el-button icon="RefreshRight" :loading="loading" round
                         @click="resetQuery">重置
              </el-button>
            </a-flex>
          </a-flex>
        </a-card>
      </div>
    </transition>
    <a-card ref="cardRef" class="card-content" hoverable>
      <template #title>
        <el-row ref="headerRef" :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:config:add']" round icon="Plus" plain type="primary" @click="handleAdd">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:config:edit']" round :disabled="single" icon="Edit" plain type="success"
                       @click="handleUpdate()">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:config:remove']" round plain :disabled="multiple" icon="Delete"
                       type="danger"
                       @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:config:export']" round icon="Download" plain type="warning"
                       @click="handleExport">
              导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:config:remove']" round plain icon="Refresh" type="info"
                       @click="handleRefreshCache">刷新缓存
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <a-spin :spinning="loading" size="large">
        <el-table :data="configList" :height="tableHeight" @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="columns[0].visible" :fixed="columns[0].fixed" align="center" type="selection"
                           min-width="55" />
          <el-table-column v-if="columns[1].visible" :fixed="columns[1].fixed" align="center" label="序号" type="index"
                           min-width="50">
            <template #default="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columns[2].visible" :fixed="columns[2].fixed" align="center" label="参数编号"
                           min-width="200" prop="configId" />
          <el-table-column v-if="columns[3].visible" :fixed="columns[3].fixed" :show-overflow-tooltip="true"
                           align="center"
                           label="参数名称" min-width="200" prop="configName" />
          <el-table-column v-if="columns[4].visible" :fixed="columns[4].fixed" :show-overflow-tooltip="true"
                           align="center"
                           label="参数键名" min-width="200" prop="configKey" />
          <el-table-column v-if="columns[5].visible" :fixed="columns[5].fixed" :show-overflow-tooltip="true"
                           align="center"
                           label="参数键值" min-width="120" prop="configValue" />
          <el-table-column v-if="columns[6].visible" :fixed="columns[6].fixed" align="center" label="系统内置"
                           min-width="100" prop="configType">
            <template #default="scope">
              <dict-tag :options="sys_yes_no" :value="scope.row.configType" />
            </template>
          </el-table-column>
          <el-table-column v-if="columns[7].visible" :fixed="columns[7].fixed" :show-overflow-tooltip="true"
                           align="center" label="备注"
                           min-width="150" prop="remark" />
          <el-table-column v-if="columns[8].visible" :fixed="columns[8].fixed" align="center" label="创建时间"
                           prop="createTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="150">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button v-hasPermi="['system:config:edit']" circle icon="Edit" plain type="success"
                           @click="handleUpdate(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button v-hasPermi="['system:config:remove']" circle plain icon="Delete" type="danger"
                           @click="handleDelete(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <template #empty>
            <a-empty />
          </template>
        </el-table>
      </a-spin>
    </a-card>
    <a-card hoverable ref="paginationRef" v-show="total>0">
      <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList" />
    </a-card>
    <!-- 添加或修改参数配置对话框 -->
    <el-drawer v-model="drawer.visible" :title="drawer.title" append-to-body close-on-click-modal size="30%">
      <el-form ref="configFormRef" :model="form" :rules="rules" label-width="20%">
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="form.configName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input v-model="form.configKey" placeholder="请输入参数键名" />
        </el-form-item>
        <el-form-item label="参数键值" prop="configValue">
          <el-input v-model="form.configValue" type="textarea" placeholder="请输入参数键值" />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-radio-group v-model="form.configType">
            <el-radio v-for="dict in sys_yes_no" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Config" lang="ts">
import { listConfig, getConfig, delConfig, addConfig, updateConfig, refreshCache } from '@/api/system/config';
import { ConfigForm, ConfigQuery, ConfigVO } from '@/api/system/config/types';
import { useElTableHeight } from '@/utils/useElTableHeight';
import useSettingsStore from '@/store/modules/settings';

const settingsStore = useSettingsStore();
const needTagsView = computed(() => settingsStore.tagsView);
/*计算表格高度*/
const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(null);
const paginationRef = ref<any>(null);
const { tableHeight } = useElTableHeight(cardRef, [headerRef, paginationRef]);

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `多选`, visible: true, fixed: true, children: [] },
  { key: 1, label: `序号`, visible: true, fixed: false, children: [] },
  { key: 2, label: `参数编号`, visible: false, fixed: false, children: [] },
  { key: 3, label: `参数名称`, visible: true, fixed: false, children: [] },
  { key: 4, label: `参数键名`, visible: true, fixed: false, children: [] },
  { key: 5, label: `参数键值`, visible: true, fixed: false, children: [] },
  { key: 6, label: `系统内置`, visible: true, fixed: false, children: [] },
  { key: 7, label: `备注`, visible: true, fixed: false, children: [] },
  { key: 8, label: `创建时间`, visible: true, fixed: false, children: [] }
]);


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));

const configList = ref<ConfigVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[string, string]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const configFormRef = ref<ElFormInstance>();
const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});
const initFormData: ConfigForm = {
  configId: undefined,
  configName: '',
  configKey: '',
  configValue: '',
  configType: 'Y',
  remark: ''
};
const data = reactive<PageData<ConfigForm, ConfigQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    configName: '',
    configKey: '',
    configType: ''
  },
  rules: {
    configName: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
    configKey: [{ required: true, message: '参数键名不能为空', trigger: 'blur' }],
    configValue: [{ required: true, message: '参数键值不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询参数列表 */
const getList = async () => {
  loading.value = true;
  const res = await listConfig(proxy?.addDateRange(queryParams.value, dateRange.value));
  configList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
/** 取消按钮 */
const cancel = () => {
  reset();
  drawer.visible = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  configFormRef.value?.resetFields();
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: ConfigVO[]) => {
  ids.value = selection.map((item) => item.configId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  drawer.visible = true;
  drawer.title = '添加参数';
};
/** 修改按钮操作 */
const handleUpdate = async (row?: ConfigVO) => {
  reset();
  const configId = row?.configId || ids.value[0];
  const res = await getConfig(configId);
  Object.assign(form.value, res.data);
  drawer.visible = true;
  drawer.title = '修改参数';
};
/** 提交按钮 */
const submitForm = () => {
  configFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.configId ? await updateConfig(form.value) : await addConfig(form.value);
      proxy?.$modal.notifySuccess('操作成功');
      drawer.visible = false;
      await getList();
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: ConfigVO) => {
  const configIds = row?.configId || ids.value;
  await proxy?.$modal.confirm('是否确认删除参数编号为"' + configIds + '"的数据项？');
  await delConfig(configIds);
  await getList();
  proxy?.$modal.notifySuccess('删除成功');
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/config/export',
    {
      ...queryParams.value
    },
    `config_${new Date().getTime()}.xlsx`
  );
};
/** 刷新缓存按钮操作 */
const handleRefreshCache = async () => {
  await refreshCache();
  proxy?.$modal.notifySuccess('刷新缓存成功');
};

onMounted(() => {
  getList();
});
</script>
